﻿using System;
using System.ComponentModel.DataAnnotations;
using EnetaMvc.Core.Domain.Common;
using EnetaMvc.Core.Repositories;
using EnetaMvc.Infrastructure;

namespace EnetaMvc.Validation
{
    public class UserValidator : BaseValidator<User>, IUserValidator
    {
        private readonly IUserRepository _userRepository;

        public UserValidator(IUserRepository userRepository)
        {
            _userRepository = userRepository;
        }
        
        public override MultiValidationResult Validate(User user)
        {
            if (user == null)
                throw new ArgumentNullException("user");

            var result = base.Validate(user);

            if (IsUserNameTaken(user))
            {
                var error = new ValidationResult("User name is already taken",new string[]{ "UserName" });
                result.Results.Add(error);
            }

            return result;
        }

        private bool IsUserNameTaken(User user)
        {
            var anotherUser = _userRepository.GetUserByUserName(user.UserName);
            if (anotherUser == null)
                return false;

            return (user.Id != anotherUser.Id);
        }
    }
}
